import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import path from 'path';
import { fileURLToPath } from 'url';

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 导入路由
import travelRoutes from './routes/travelRoutes.js';
import uploadRoutes from './routes/uploadRoutes.js';
import authRoutes from './routes/authRoutes.js';
import auditorRoutes from './routes/auditorRoutes.js';
import adminRoutes from './routes/adminRoutes.js';

class App {
    constructor() {
        this.app = express();
        this.configureMiddlewares();
        this.setupRoutes();
    }

    configureMiddlewares() {
        // 基本中间件
        this.app.use(express.json());
        this.app.use(express.urlencoded({ extended: true }));
        // this.app.options('*', cors());
        // 安全相关中间件
        // this.app.use(cors({
        //   origin: ['http://localhost:5174'],
        //   credentials: true
        // }));

        // 解决跨域请求
        this.app.use(cors({
            origin: '*',  // 允许的前端域名
            methods: ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'],         // 允许的请求方法
            allowedHeaders: ['Content-Type', 'Authorization'],
            credentials: true                 // 是否允许携带 Cookies
        }));

        this.app.use(helmet());
        // 性能优化中间件
        this.app.use(compression());

        // 日志中间件
        this.app.use(morgan('dev'));

        // 配置静态文件服务
        this.app.use('/api/uploads', express.static(path.join(__dirname, '../public/uploads')));
        this.app.use(express.static(path.join(__dirname, '../public')));

        // 限制请求速率
        const limiter = rateLimit({
            windowMs: 15 * 60 * 1000, // 15分钟
            max: 100, // 每个IP在windowMs内最多100个请求
            standardHeaders: true,
            legacyHeaders: false,
        });
        this.app.use(limiter);
    }
    setupRoutes() {
        // API路由
        this.app.use('/api/auth', authRoutes); // 添加认证路由
        this.app.use('/api/travels', travelRoutes);
        this.app.use('/api/upload', uploadRoutes);
        this.app.use('/api/auditors', auditorRoutes);
        this.app.use('/api/admin', adminRoutes); // 添加管理员路由

        // 根路由 - API健康检查
        this.app.get('/', (req, res) => {
            res.json({
                message: '旅游日记平台API服务运行正常',
                version: '0.1.0',
                timestamp: new Date().toISOString()
            });
        });

        // 处理404
        this.app.use((req, res) => {
            res.status(404).json({
                success: false,
                error: '请求的资源不存在'
            });
        });
    }
}

export default new App().app;